package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"guanggao/cache"
	"guanggao/models"
)

type GuanggaoController struct {
	beego.Controller
}
type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *GuanggaoController) Add() {
	name := c.GetString("name")
	address := c.GetString("address")
	rq := c.GetString("rq")
	img := c.GetString("img")
	lj := c.GetString("lj")
	px := c.GetString("px")
	zd := c.GetString("zd")
	zt := c.GetString("zt")
	var gu models.Guanggao
	gu.Name = name
	gu.Address = address
	gu.Rq = rq
	gu.Img = img
	gu.Lj = lj
	gu.Px = px
	gu.Zd = zd
	gu.Zt = zt
	if gu.Name == "" || gu.Address == "" || gu.Rq == "" || gu.Img == "" || gu.Lj == "" || gu.Px == "" || gu.Zd == "" || gu.Zt == "" {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if gu.Add() != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	h, _ := gu.List()
	hh, _ := json.Marshal(h)
	cache.Rdb.Set(cache.Ctx, "wes", hh, 0)
	c.Data["json"] = JsonR{
		Code: 200,
		Msg:  "添加成功",
		Data: nil,
	}
	c.ServeJSON()
}
func (c *GuanggaoController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	address := c.GetString("address")
	rq := c.GetString("rq")
	img := c.GetString("img")
	lj := c.GetString("lj")
	px := c.GetString("px")
	zd := c.GetString("zd")
	zt := c.GetString("zt")
	var gu models.Guanggao
	gu.ID = uint(id)
	gu.Name = name
	gu.Address = address
	gu.Rq = rq
	gu.Img = img
	gu.Lj = lj
	gu.Px = px
	gu.Zd = zd
	gu.Zt = zt
	if id < 1 {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "参数错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if gu.Update() != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	h, _ := gu.List()
	hh, _ := json.Marshal(h)
	cache.Rdb.Set(cache.Ctx, "wes", hh, 0)
	c.Data["json"] = JsonR{
		Code: 200,
		Msg:  "修改成功",
		Data: nil,
	}
	c.ServeJSON()
}
func (c *GuanggaoController) Del() {
	id, _ := c.GetInt("id")
	var gu models.Guanggao
	gu.ID = uint(id)
	if id < 1 {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "参数错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if gu.Del() != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	h, _ := gu.List()
	hh, _ := json.Marshal(h)
	cache.Rdb.Set(cache.Ctx, "wes", hh, 0)
	c.Data["json"] = JsonR{
		Code: 200,
		Msg:  "删除成功",
		Data: nil,
	}
	c.ServeJSON()
}
